<template>
    <el-main>
        <el-card style="height: 80px;width: 550px;">
            <!-- 查询条件区域 -->
            <el-form :inline="true" ref="searchForm" class="demo-form-inline" label-width="80px" size="small">
                <el-form-item>
                    <el-input v-model="searchModel.fluxName" placeholder="请输入燃料名称" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="search()">查询</el-button>
                    <!-- <el-button icon="el-icon-refresh-right">重置</el-button> -->
                    <el-button type="success" icon="el-icon-plus" @click="openAddWindow()">新增</el-button>
                    <!-- 导出excel表格 -->
                    <el-button :loading="downloadLoading" style="margin:0 0 10px 10px;" type="primary"
                        icon="el-icon-document" @click="handleDownload">
                        Export Excel
                    </el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <div style="height: 30px; background-color: transparent;"></div>

        <el-card>
            <!-- 数据表格 -->
            <el-table :data="tableData" stripe style="width: 100%" ref="fluxTable" selction="selectedData"
                @selection-change="handleSelectionChange">
                <!-- 添加一个序号列，使用type="index" -->
                <el-table-column type="index" label="序号" label-class-name="bold-header" fixed="left" />
                <el-table-column prop="fluxName" label="熔剂名称" label-class-name="bold-header" fixed="left" />
                <!-- 添加一个选择列，使用type="selection" -->
                <el-table-column prop="isSelected" type="index" label="选择" width="60px" label-class-name="bold-header">
                    <template slot-scope="scope">
                        <el-checkbox v-model="scope.row.isSelected" :checked="scope.row.isSelected"
                            @change="updateIsSelected(scope.row)"></el-checkbox>
                    </template>
                </el-table-column>
                <!-- prop:填写数据的属性名称 -->

                <el-table-column prop="tfe" label="TFe" label-class-name="bold-header" />
                <el-table-column prop="sio2" label="SiO2" label-class-name="bold-header" />
                <el-table-column prop="cao" label="CaO" label-class-name="bold-header" />
                <el-table-column prop="mgo" label="MgO" label-class-name="bold-header" />
                <el-table-column prop="al2o3" label="Al2O3" label-class-name="bold-header" />
                <el-table-column prop="p" label="P" label-class-name="bold-header" />
                <el-table-column prop="s" label="S" label-class-name="bold-header" />
                <el-table-column prop="mn" label="Mn" label-class-name="bold-header" />
                <el-table-column prop="h2o" label="H2O" label-class-name="bold-header" />
                <el-table-column prop="burn" label="Burn" label-class-name="bold-header" />
                <el-table-column prop="price" label="价格" label-class-name="bold-header" />
                <el-table-column prop="min" label="下限" label-class-name="bold-header" />
                <el-table-column prop="max" label="上限" label-class-name="bold-header" />
                <el-table-column label="操作" width="200" label-position="center" label-class-name="bold-header">
                    <template slot-scope="scope">
                        <el-button size="mini" @click="handleEdit(scope.row)" icon="el-icon-s-promotion">编辑</el-button>
                        <el-button size="mini" type="danger" @click="handleDelete(scope.row)"
                            icon="el-icon-delete-solid">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- <el-table :data="tableData" style=" margin-bottom: 20px" row-key="id">
            
        </el-table> -->

            <!-- 添加和修改窗口 -->
            <system-dialog :title="deptDialog.title" :visible="deptDialog.visible" :width="deptDialog.width"
                :height="deptDialog.height" @onClose="onClose" @onConfirm="onConfirm">
                <div slot="content">
                    <el-form :model="flux" ref="deptForm" :rules="rules" label-width="100px" :inline="true" size="small">
                        <el-form-item label="熔剂名称" prop="fluxName">
                            <el-input v-model="flux.fluxName"></el-input>
                        </el-form-item>
                        <el-form-item label="TFe含量" prop="tfe">
                            <el-input v-model="flux.tfe"></el-input>
                        </el-form-item>
                        <el-form-item label="SiO2含量" prop="sio2">
                            <el-input v-model="flux.sio2"></el-input>
                        </el-form-item>
                        <el-form-item label="CaO含量" prop="cao">
                            <el-input v-model="flux.cao"></el-input>
                        </el-form-item>
                        <el-form-item label="MgO含量" prop="mgo">
                            <el-input v-model="flux.mgo"></el-input>
                        </el-form-item>
                        <el-form-item label="Al2O3含量" prop="al2o3">
                            <el-input v-model="flux.al2o3"></el-input>
                        </el-form-item>
                        <el-form-item label="P含量" prop="p">
                            <el-input v-model="flux.p"></el-input>
                        </el-form-item>
                        <el-form-item label="S含量" prop="s">
                            <el-input v-model="flux.s"></el-input>
                        </el-form-item>
                        <el-form-item label="Mn含量" prop="mn">
                            <el-input v-model="flux.mn"></el-input>
                        </el-form-item>
                        <el-form-item label="H2O含量" prop="h2o">
                            <el-input v-model="flux.h2o"></el-input>
                        </el-form-item>
                        <el-form-item label="Burn含量" prop="burn">
                            <el-input v-model="flux.burn"></el-input>
                        </el-form-item>
                        <el-form-item label="价格" prop="price">
                            <el-input v-model="flux.price"></el-input>
                        </el-form-item>
                        <el-form-item label="下限" prop="min">
                            <el-input v-model="flux.min"></el-input>
                        </el-form-item>
                        <el-form-item label="上限" prop="max">
                            <el-input v-model="flux.max"></el-input>
                        </el-form-item>
                    </el-form>
                </div>
            </system-dialog>

            <!-- 分页器 -->
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
                :page-sizes="[1, 2, 5, 10]" :page-size="size" layout="total, sizes, prev, pager, next, jumper"
                :total="total" style="margin-top: 10px">
            </el-pagination>
        </el-card>

        <div style="height: 10px; background-color: white;"></div>
        <!-- 添加一个路由跳转，使用router-link -->
        <!-- <router-link :to="{ path: '/orebleeding', query: { fluxData: JSON.stringify(selectedData) } }">
            <el-button type="primary" style="height: 40px;padding: 6px" icon="el-icon-circle-check">添加所选熔剂到配料界面</el-button>
        </router-link> -->
    </el-main>
</template>

<script>
//导入department脚本文件
import departmentApi from "@/api/department";
import iconoreApi from "@/api/iconore";
import fuelApi from "@/api/fuel";
import fluxApi from "@/api/flux";
//导入对话框组件
import SystemDialog from "@/components/system/SystemDialog1.vue";

export default {
    name: "flux",
    components: {
        SystemDialog,
    },
    data() {
        return {
            downloadLoading: false,//导出时按钮
            searchModel: {
                fluxName: "", //熔剂名称
            },
            tableData: [],//表格数据
            page: 1,
            size: 10,
            total: 1,
            selectedData: [], // 存储被选择的原料的数据
            deptDialog: {
                title: "",
                visible: false,
                width: 380,
                height: 500,
            },
            flux: {
                //对应到department里面的属性
                id: "",
                fluxName: "",
                tfe: "",
                sio2: "",
                cao: "",
                mgo: "",
                al2o3: "",
                p: "",
                s: "",
                mn: "",
                h2o: "",
                burn: "",
                price: "",
                isSelected: "",
                min: "",
                max: ""
            },
            rules: {
                fluxName: [
                    { required: true, message: "请输入熔剂名称", trigger: "change" },
                ],
                tfe: [{ required: true, message: "请输入内容", trigger: "change" }],
                sio2: [{ required: true, message: "请输入内容", trigger: "change" }],
                cao: [{ required: true, message: "请输入内容", trigger: "change" }],
                mgo: [{ required: true, message: "请输入内容", trigger: "change" }],
                al2o3: [{ required: true, message: "请输入内容", trigger: "change" }],
                p: [{ required: true, message: "请输入内容", trigger: "change" }],
                s: [{ required: true, message: "请输入内容", trigger: "change" }],
                mn: [{ required: true, message: "请输入内容", trigger: "change" }],
                h2o: [{ required: true, message: "请输入内容", trigger: "change" }],
                burn: [{ required: true, message: "请输入内容", trigger: "change" }],
                price: [{ required: true, message: "请输入价格", trigger: "change" }],
                min: [{ required: true, message: "请输入内容", trigger: "change" }],
                max: [{ required: true, message: "请输入内容", trigger: "change" }],
            },

        };
    },
    //初始化时调用
    created() {
        //调用查询熔剂列表
        this.search();
        this.selectedData = "";
    },

    methods: {

        /**
         *更新选择状态
         */
        async updateIsSelected(row) {

            //数据回显
            this.$objCopy(row, this.flux);
            console.log(this.flux);
            if (this.flux.isSelected) {
                this.flux.isSelected = 1;
            } else {
                this.flux.isSelected = 0;
            }
            console.log(this.flux);
            let res = await fluxApi.updateFlux(this.flux);
            console.log(res);
            if (res.success) {
                //提示成功
                // this.$message.success("添加成功");
                //刷新数据
                this.search();
            } else {
                this.$message.error("添加失败");
            }
            window.location.reload();
        },

        // 定义一个函数，用来处理选择项变化时的逻辑
        handleSelectionChange(selection) {
            // 将选择的行的数据赋值给selectedData数组
            this.selectedData = selection;
            // 你可以在这里做一些其他的操作，例如打印或发送选中的数据
            console.log(this.selectedData);
        },

        /**
         * 导出excel数据
         */
        handleDownload() {
            this.downloadLoading = true
            import('@/vendor/Export2Excel').then(excel => {
                const tHeader = ['熔剂', 'TFe', 'SiO2', 'CaO', 'MgO', 'Al2O3', 'P', 'S', 'Mn', 'H2O', 'Burn']
                const filterVal = ['fluxName', 'tfe', 'sio2', 'cao', 'mgo', 'al2o3', 'p', 's', 'mn', 'h2o', 'burn']
                const list = this.tableData
                const data = this.formatJson(filterVal, list)
                excel.export_json_to_excel({
                    header: tHeader,
                    data,
                    filename: '熔剂信息.xlsx',
                    autoWidth: this.autoWidth,
                    bookType: 'xlsx'
                })
                this.downloadLoading = false
            })
        },
        formatJson(filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => {
                if (j === 'timestamp') {
                    return parseTime(v[j])
                } else {
                    return v[j]
                }
            }))
        },

        /**
         * 编辑熔剂
         */
        handleEdit(row) {
            //数据回显
            this.$objCopy(row, this.flux);
            //设置窗口的标题
            this.deptDialog.title = "编辑熔剂数据";
            //显示窗口
            this.deptDialog.visible = true;
        },
        async handleDelete(row) {
            //确认是否删除
            let confirm = window.confirm("确认要删除该数据吗？");
            if (confirm) {
                //发送删除请求
                let res = await fluxApi.deleteFlux({ id: row.id });
                if (res.success) {
                    //提示成功
                    this.$message.success(res.message);
                    //刷新数据
                    this.search();
                } else {
                    this.$message.error(res.message);
                }
            }
        },

        /**
         * 查询燃料列表
         */
        async search() {
            //发送查询请求
            // let res = await departmentApi.getDepartmentList(this.departmentName)
            // .then获取请求成功，.catch获取请求失败，并抛出异常，停止往下执行
            await fluxApi
                .findFluxList(this.searchModel)
                .then((res) => {
                    //查看请求成功的数据
                    console.log(res);
                    if (res.success) {
                        // this.tableData = res.data;
                        this.total = res.data.length;
                        let start = (this.page - 1) * this.size; // 计算当前页的起始索引
                        let end = start + this.size; // 计算当前页的结束索引
                        this.tableData = res.data.slice(start, end); // 截取当前页的数据
                    }
                })
                .catch((err) => {
                    // ElMessage.error("请求失败")
                    throw new Error("请求失败");
                });
            // console.log(res)
            // //判断是否成功
            // if (res.success) {
            //     this.tableData = res.data
            // }
        },

        /**
         * 打开添加窗口
         */
        openAddWindow() {
            //清空表单数据,第一个参数是表单的ref值，后面一个参数是表单数据
            this.$resetForm("deptForm", this.flux);

            this.deptDialog.title = "新增熔剂";
            this.deptDialog.visible = true;
        },

        /**
         * 窗口的关闭事件
         */
        onClose() {
            this.deptDialog.visible = false;
        },
        /**
         * 窗口确认事件
         */
        onConfirm() {
            //进行表单验证
            this.$refs.deptForm.validate(async (valid) => {
                //如果验证通过
                if (valid) {
                    let res = null;

                    //判断当前是新增还是修改（判断条件，判断当前dept对象的id属性是否为空）
                    //为空发送新增请求，不为空发送修改请求
                    if (this.flux.id === "") {
                        //发送添加请求
                        res = await fluxApi.addFlux(this.flux);
                    } else {
                        //发送修改请求
                        console.log(this.flux);
                        if (this.flux.isSelected) {
                            this.flux.isSelected = 1;
                        } else {
                            this.flux.isSelected = 0;
                        }
                        console.log(this.flux);
                        res = await fluxApi.updateFlux(this.flux);
                        console.log(res);
                    }

                    if (res.success) {
                        //提示成功
                        this.$message.success(res.message);
                        //刷新数据
                        this.search();
                        //关闭窗口
                        this.deptDialog.visible = false;
                    } else {
                        this.$message.error(res.message);
                    }
                }
            });
        },

        /**
         * 页面大小改变时分页器操作
         */
        handleSizeChange(val) {
            this.size = val;
            this.search();
        },
        /**
         * 当前页码改变时分页器操作
         */
        handleCurrentChange(val) {
            this.page = val;
            this.search();
        },
    },
};
</script>

<style>
.bold-header {
    font-weight: bold;
    color: black;
    /* background-color: azure; */
}
</style>
